package com.zzz.demo.controller;

import com.alibaba.fastjson.JSON;
import com.ccpp.demo.entity.LearnResource;
import com.ccpp.demo.entity.User;
import com.ccpp.demo.service.LearnService;
import com.ccpp.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.zzz.demo.async.IAsynchronDealDataCheck;
import com.zzz.demo.dao.LearnMapper;
import com.zzz.demo.dao.UserMapper;
import com.zzz.demo.interf.impl.AsyncTaskAdapter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

/**
 * @author ZZZ
 * @version 1.0
 * @date 2018/7/17 0017
 */
@ApiModel(value = "测试类",description = "测试类")
@Controller
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAsynchronDealDataCheck asynchronDealDataCheck;
    @Autowired
    private LearnMapper learnMapper;
    @Autowired
    private UserService userService;



    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(AsyncTaskAdapter.class);

    @RequestMapping("/testAsync")
    public @ResponseBody String testAsync(){
        // 执行异步任务
        StopWatch stopWatch = new StopWatch("AsynchronDealDataCheck");
        asynchronDealDataCheck.setAsyncTaskListener(new AsyncTaskAdapter() {
            @Override
            public void onStart() {
                super.onStart();
                if(!stopWatch.isRunning()){
                    stopWatch.start();
                }
            }
            @Override
            public void onSuccess() {
                super.onSuccess();
                if(stopWatch.isRunning()){
                    stopWatch.stop();
                }
                if(logger.isInfoEnabled()) {
                    logger.info("本次处理数据：1条，共耗时"+stopWatch.getTotalTimeMillis()+"ms");
                    stopWatch.prettyPrint();
                }
            }
        });
        //执行异步方法
        asynchronDealDataCheck.handleCheck();
        return "执行完毕：" + UUID.randomUUID();
    }

    @ApiOperation(value = "获取所有用户",tags = {"用户管理"})
    @RequestMapping("getUser")
    public @ResponseBody User getUser(){
        return new User(){{
            setUserName("朱振振");
            setGender("男");
            setPassWord("admin");
        }};
    }

    @ApiOperation(value = "跳转首页",tags = {"用户管理"})
    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @ApiOperation(value = "获取所资源列表")
    @RequestMapping("/getAll")
    public @ResponseBody  List<LearnResource> getAll() {
        PageHelper.startPage(1, 2);
        return learnMapper.getAll();
    }

    @Autowired
    private LearnService learnService;

    @RequestMapping("add")
    public @ResponseBody void addLearnResource() {
        learnService.add(new LearnResource(){{
            setAuthor("zzz");
            setTitle("这是标题");
            setUrl("wwww.baidum.com");
        }});
    }

    @RequestMapping(value = "testSession")
    public @ResponseBody String testSession(ModelMap map, HttpSession httpSession) {
        User user = new User() {{
            setUserName("zzz");
            setPassWord("admin");
        }};
        map.put("title", "第一个应用：sessionID=" + httpSession.getId());
        httpSession.setAttribute("loginUser", JSON.toJSONString(user));
        Object loginUser = httpSession.getAttribute("loginUser");
        System.err.println(loginUser);
        System.out.println("sessionID=" + httpSession.getId());
        return "sessionID=" + httpSession.getId();
    }

    @PostMapping(value="/login")
    public @ResponseBody String login(User user){
        System.out.println(JSON.toJSON(userService.getUserById(1)));
        Subject subject = SecurityUtils.getSubject();
        try {
            if(!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassWord());
                token.setRememberMe(true);
                subject.login(token);
                Session session = subject.getSession();
                System.out.println(session.getId() + ":" + session.getTimeout());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed";
        }
        return "Success";
    }

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @RequestMapping("testMybatis")
    public @ResponseBody List<User> testMybatis() {
        System.out.println(sqlSessionFactory);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = configuration.getMapper(UserMapper.class, sqlSession);
        List<User> userList = userMapper.getUser();
        System.out.println(JSON.toJSONString(userList));
        return userList;
    }

}
